<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" :rules="rules" validate-trigger="submit" err-show-type="undertext">
			<uni-forms-item name="username" required>
				<uni-easyinput :inputBorder="false" class="easyinput" :placeholder="$t('register.usernamePlaceholder')" v-model="formData.username" trim="both" />
			</uni-forms-item>
			<uni-forms-item name="nickname" required>
				<uni-easyinput
					:inputBorder="false"
					class="easyinput"
					:placeholder="$t('register.nicknamePlaceholder')"
					v-model="formData.nickname"
					trim="both"
					style="width: 660rpx;"
				/>
			</uni-forms-item>
			<uni-forms-item name="password" v-model="formData.password" required>
				<uni-easyinput
					:inputBorder="false"
					class="easyinput"
					:placeholder="$t('register.passwordDigitsPlaceholder')"
					type="password"
					v-model="formData.password"
					trim="both"
				/>
			</uni-forms-item>
			<uni-forms-item name="pwd2" v-model="formData.pwd2" required>
				<uni-easyinput :inputBorder="false" class="easyinput" :placeholder="$t('register.passwordAgain')" type="password" v-model="formData.pwd2" trim="both" />
			</uni-forms-item>
			<uni-agreements @setAgree="agree = $event"></uni-agreements>
			<button class="send-btn" type="primary" @click="submit">{{ $t('register.registerAndLogin') }}</button>
		</uni-forms>
	</view>
</template>

<script>
import { mapMutations, mapGetters } from 'vuex';
import rules from './validator.js';
import mixin from '../common/login-page.mixin.js';
import { login ,updateUser ,queryPersonalInfo} from '../../../../services/index.js';
	import {TUser} from '../../../../entity/index.js';
export default {
	mixins: [mixin],
	data() {
		return {
			formData: {
				username: '',
				nickname: '',
				password: '',
				pwd2: ''
			},
			rules,
			agree: false
		};
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	onLoad() {
		uni.setNavigationBarTitle({
			title: this.$t('register.navigationBarTitle')
		});
	},
	computed: {
		...mapGetters('user', ['cookieTclGet'])
	},
	methods: {
		...mapMutations('user', ['setCookieTcl']),
		/**
		 * 触发表单提交
		 */
		 submit() {
			if (!this.agree) {
				return uni.showToast({
					title: this.$t('common').noAgree,
					icon: 'none'
				});
			}
			uni.showLoading({
				mask: true
			});
			this.$refs.form
				.validate()
				.then( async res => {
					const { username, password } = res;
					const encryptPwd = this.$utils.encrypt(password);
					const { success, data:{jsessionid,jsessiontoken,data}} = await login({ loginId: username, password: encryptPwd })
					let msg = '';
					if (success) {
						if (!jsessionid || !jsessiontoken || !data) {
							msg = '验证T学堂登录失败,返回参数异常';
							return;
						}
						// 创建Cookie
						const cookieObj = {
							SESSION: jsessionid,
							JSESSIONTOKEN: jsessiontoken,
							SIAMTGT: data,
							USERTOKEN: username
						};
						let cookieStr = '';
						for (let [key, value] of Object.entries(cookieObj)) {
							cookieStr += `${key}=${value};`;
						}
						if (cookieStr) {
							// 保存到store
							this.setCookieTcl(cookieStr);
							// //保存到本地持久化存储
							uni.setStorageSync('COOKIE_TCL', cookieStr);
							// 注册登录
							this.submitForm({ ...res, password: encryptPwd });
						}
					} else {
						msg = '验证T学堂登录失败,请检查账号密码是否有误';
					}
					if (!msg) return;
					uni.showModal({
						content: msg,
						showCancel: false
					});
				})
				.catch(errors => {
					console.log(errors);
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		async submitForm(params) {
		 const {username} = params
		 const  {result} =  await uniCloud.callFunction({
				name: 'uni-id-cf',
				data: {
					action: 'register',
					params
				},
			});
			const {code,msg} = result
			if (code === 0) {
				
				  const user = new TUser()
				  const {success,data:{data}} =  await  queryPersonalInfo()
				  user.fill(data)
				  user.sex = user.sex_id == '009' ? '男' : '女'
				
				//注册成功写入用户信息
				  await  updateUser({
					  data:{
					  user_tcl:user
					} ,
				   where:{
					  username
				  }})
				
				this.loginSuccess(result);
			} else {
				uni.showModal({
					content: msg,
					showCancel: false
				});
			}
			
			
		}
	}
};
</script>

<style>
@import url('../common/login-page.css');
.uni-container {
	padding: 15px;
}
.send-btn {
	margin-top: 5px;
}
.uni-container ::v-deep .uni-forms-item__label {
	width: 15px !important;
}
</style>
